<?php

namespace common\helpers;

use common\models\c2\entity\ActivityModel;
use common\models\c2\entity\ActivityPlayerModel;
use common\models\c2\statics\ActivityPlayerState;
use common\rest\statics\ResponseDatum;
use Yii;
use yii\redis\Connection;

class VoteHelper
{
    /**
     * @param $player
     * @param $userId
     * @return string
     */
    public static function checkLimit($player, $userId)
    {

        if (is_null($player) || $player->state != ActivityPlayerState::STATE_CHECKED) {
            return Yii::t('app.c2', 'Player Disabled');
        }
        $activity = $player->activity;
        if (time() > strtotime($activity->end_at)) {
            return Yii::t('app.c2', 'Activity Disabled');
        }
        $key = self::getVotedKey($userId, $player->id);
        $redis = \Yii::$app->redis;
        // $votedNum = $redis->get($key);
        $votedNum = $redis->executeCommand('GET', [$key]);
        if ($votedNum >= $activity->vote_number_limit) {
            return Yii::t('app.c2', 'You can vote {s1} once day.', [
                's1' => $activity->vote_number_limit]);
        }
        return "ycan";
    }

    /**
     * 设置活动选手排名
     * @param $redis Connection
     * @param $playerModel ActivityPlayerModel
     * @throws \yii\db\Exception
     */
    public static function setActivityPlayerRank($redis, $playerModel)
    {
        $kActivity = K_ACTIVITY_RANK . $playerModel->activity_id;
        $kPlayer = K_PLAYER . $playerModel->id;
        $redis->executeCommand('ZADD', [$kActivity, $playerModel->total_vote_number, $kPlayer]);
    }

    public static function getVotedKey($userId, $playerId)
    {
        return K_USER_ID . $userId . K_PLAYER_ID . $playerId . '_' . date('Y/m/d', time());
        // return printf('%s%d_%s%d_%s', K_USER_ID, $userId, K_PLAYER_ID, $playerId, date('Y-m-d', time()));
    }

    public static function getActivityPlayerRank($redis, $playerModel)
    {
        return K_ACTIVITY_RANK . $playerModel->activity_id;
    }

}
